package com.douwong.student.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;


/**
 *  
 * 图片缩放View，视图固定居中显示、双击变为原图大小
 * @author Tab.lv
 *
 */
public class ScaleImageView extends AppCompatImageView{

	private PointF point0 = new PointF();
	private PointF pointM = new PointF();

	private final float ZOOM_MIN_SPACE = 10f;

	// 设定事件模式
	private final int NONE = 0;
	private final int DRAG = 1;
	private final int ZOOM = 2;
	private int mode = NONE;

	private Matrix matrix = new Matrix();
	private Matrix savedMatrix = new Matrix();

	// 获取屏幕分辨率。以2048*1024为例
	private int displayHeight = 0;
	private int displayWidth = 0;

	private float minScale = 1f;
	private float maxScale = 10f;
	private float currentScale = 1f;
	private float oldDist;

//	private Bitmap bm;
	private int imgWidth;
	private int imgHeight;
	
	private Context mContext=null;
	private String TAG="ScaleImageView";
	
	private GestureDetector mDetector;
	public boolean isDrag = true;
	private Bitmap bitmap;

	public ScaleImageView(Context context) {
		this(context,null);
	}

	public ScaleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	public ScaleImageView(Context context, AttributeSet attrs) {
		this(context, attrs,0);
		this.mContext=context;		
//		init();
	}


	public void setDispResource(Bitmap bm, int w, int h) {
		if(bm==null){
			throw new IllegalArgumentException("bm can't null.....");
		}
		bitmap=bm;
		imgWidth = bm.getWidth();
		imgHeight = bm.getHeight();
		displayHeight=h;
		displayWidth=w;
//		Log.d(TAG, displayWidth+" :==================== "+displayHeight);
		setImageBitmap(bm);		
		minScale = getMinScale();		
		matrix.setScale(minScale, minScale);		
		center();	
		setImageMatrix(matrix);
		mDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() {
	            @Override
	            public boolean onDoubleTap(MotionEvent e) {
	            	zoomToOriginal();	                
	                return super.onDoubleTap(e);
	    }			
	   });
	}
	
	public void zoomToOriginal() {
		// TODO Auto-generated method stub
		minScale = getMinScale();		
		matrix.setScale(minScale, minScale);
		setImageMatrix(matrix);		
		center();
	}
	
	
	private void whenMove(MotionEvent event) {
		switch (mode) {
		case DRAG:
			matrix.set(savedMatrix);
			matrix.postTranslate(event.getX() - point0.x, event.getY()
					- point0.y);
			break;
		case ZOOM:
			float newDist = spacing(event);
			if (newDist > ZOOM_MIN_SPACE) {
				matrix.set(savedMatrix);
				float sxy = newDist / oldDist;
				matrix.postScale(sxy, sxy, pointM.x, pointM.y);
			}
			break;
		}
	}

	
	@Override
	protected boolean setFrame(int l, int t, int r, int b) {
		// TODO Auto-generated method stub
//		displayWidth=r-l;
//		displayHeight=b-t;		
//		Log.d(TAG, displayWidth+" =======:====== "+displayHeight);
		return super.setFrame(l, t, r, b);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if(isDrag){
			
//			if (mDetector!=null&&mDetector.onTouchEvent(event)) {
//	            return true;
//	        }
			if(bitmap==null){
				return true;
			}
			switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
				savedMatrix.set(matrix);
				point0.set(event.getX(), event.getY());
				mode = DRAG;
				break;
			case MotionEvent.ACTION_POINTER_DOWN:
				oldDist = spacing(event);
				if (oldDist > ZOOM_MIN_SPACE) {
					savedMatrix.set(matrix);
					setMidPoint(event);
					mode = ZOOM;
				}
				break;
			case MotionEvent.ACTION_UP:
			case MotionEvent.ACTION_POINTER_UP:
				mode = NONE;
				break;
			case MotionEvent.ACTION_MOVE:
				whenMove(event);
				break;

			}
			setImageMatrix(matrix);
			checkView();
		}
		return true;
	}

	/**
	 * 两个触点的距离
	 * @param event
	 * @return
	 */
	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return (float) Math.sqrt(x * x + y * y);
	}
	

	private void setMidPoint(MotionEvent event) {
		float x = event.getX(0) + event.getY(1);
		float y = event.getY(0) + event.getY(1);
		pointM.set(x / 2, y / 2);
	}

	/**
	 * 图片居中
	 */
	public void center() {
		RectF rect = new RectF(0, 0, imgWidth, imgHeight);
		matrix.mapRect(rect);
		float width = rect.width();
		float height = rect.height();
		float dx = 0;
		float dy = 0;

		if (width < displayWidth)
			dx = displayWidth / 2 - width / 2 - rect.left;
		else if (rect.left > 0)
			dx = -rect.left;
		else if (rect.right < displayWidth)
			dx = displayWidth - rect.right;

		if (height < displayHeight)
			dy = displayHeight / 2 - height / 2 - rect.top;
		else if (rect.top > 0)
			dy = -rect.top;
		else if (rect.bottom < displayHeight)
			dy = displayHeight - rect.bottom;

		matrix.postTranslate(dx, dy);
	}

	// 获取最小缩放比例
	private float getMinScale() {
		float sx = (float) displayWidth / imgWidth;
		float sy = (float) displayHeight / imgHeight;
		float scale = sx < sy ? sx : sy;
		return scale;
	}

	// 检查约束条件，是否居中，空间显示是否合理
	public void checkView() {
		currentScale = getCurrentScale();
		if (mode == ZOOM) {
			if (currentScale < minScale) {
				matrix.setScale(minScale, minScale);
			}
			if (currentScale > maxScale) {
				matrix.set(savedMatrix);
			}
		}
		center();
	}

	// 图片当前的缩放比例
	private float getCurrentScale() {
		float[] values = new float[9];
		matrix.getValues(values);
		return values[Matrix.MSCALE_X];
	}

	public Bitmap getContentBitmap(){
		
		return bitmap;
	}
	

}
